package com.shenmazong.scheduling;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.dto.TbJob;
import com.shenmazong.mapper.TbJobMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 阿瑞
 * @version 1.0
 * @description TODO
 * @class JobCache ???
 * @date 2021/9/22 21:08
 */
@Component
public class JobCache {
    @Autowired
    private TbJobMapper tbJobMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
//    @Scheduled(fixedRate = 1000*5)
    public void mysqlToEs(){
        if (!elasticsearchRestTemplate.indexOps(TbJob.class).exists()){
            elasticsearchRestTemplate.indexOps(TbJob.class).create();
            Document mapping = elasticsearchRestTemplate.indexOps(TbJob.class).createMapping();
            elasticsearchRestTemplate.indexOps(TbJob.class).putMapping(mapping);
        }
        List<TbJob> list = tbJobMapper.selectList(new QueryWrapper<TbJob>().lambda().eq(TbJob::getJobAudit, 0));
        if (list.size()==0){
            System.err.println("没有需要同步的数据");
        }else {
            elasticsearchRestTemplate.save(list);
            for (TbJob job : list) {
                job.setJobAudit((byte) 1);
                tbJobMapper.updateById(job);
            }
            System.err.println("同步成功");
        }

    }
}
